/*
 * Duplicate Detector Copyright (C) 2010 Marco Biscaro <marcobiscaro2112@gmail.com>
 * 
 * This file is part of Duplicate Detector.
 *
 * Duplicate Detector is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Duplicate Detector is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Duplicate Detector.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.duplicatedetector.controller;

import static com.googlecode.duplicatedetector.i18n.Messages._;

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import com.googlecode.duplicatedetector.i18n.Keys;
import com.googlecode.duplicatedetector.model.FileTreeModel;
import com.googlecode.duplicatedetector.util.Logger;
import com.googlecode.duplicatedetector.view.FileDetailsPanel;

/**
 * Confirms and deletes a file.
 * 
 * @author Marco Biscaro
 */
public class DeleteFileActionListener implements ActionListener, Keys {

	private static final Logger LOGGER = new Logger(
			DeleteFileActionListener.class);
	private FileDetailsPanel fileDetailsPanel;
	private FileTreeModel fileTreeModel;

	public DeleteFileActionListener(FileDetailsPanel fileDetailsPanel,
			FileTreeModel fileTreeModel) {
		this.fileDetailsPanel = fileDetailsPanel;
		this.fileTreeModel = fileTreeModel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		File file = fileDetailsPanel.getFile();
		if (file == null) {
			return;
		}
		Window parent = SwingUtilities.getWindowAncestor(fileDetailsPanel);
		int result = JOptionPane.showOptionDialog(parent, _(CONFIRM_DELETE),
				_(CONFIRM), JOptionPane.YES_OPTION,
				JOptionPane.QUESTION_MESSAGE, null, new Object[] { _(YES),
						_(NO) }, _(NO));
		if (result == JOptionPane.YES_OPTION) {
			if (file.delete()) {
				fileTreeModel.remove(file);
				fileDetailsPanel.setFile(null);
				LOGGER.info("File " + file + " deleted");
			} else {
				LOGGER.error("Could not delete file " + file);
				JOptionPane.showMessageDialog(parent, _(ERROR_DELETE),
						_(ERROR), JOptionPane.ERROR_MESSAGE);
			}
		}
	}

}
